package client

import (
	product "0507zk/common/proto"
	"context"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, in product.ProductClient) (interface{}, error)

func ProductClient(ctx context.Context, Handlers Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := product.NewProductClient(dial)

	res, err := Handlers(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func SendSms(ctx context.Context, req *product.SendSmsReq) (*product.SendSmsResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductClient) (interface{}, error) {
		sms, err := in.SendSms(ctx, req)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.SendSmsResp), nil
}

func UserLogin(ctx context.Context, req *product.UserLoginReq) (*product.UserLoginResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductClient) (interface{}, error) {
		sms, err := in.UserLogin(ctx, req)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.UserLoginResp), nil
}
func UserList(ctx context.Context, req *product.ProductListReq) (*product.ProductListResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductClient) (interface{}, error) {
		sms, err := in.ProductList(ctx, req)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductListResp), nil
}
